import React, { useState, useEffect } from 'react';
import { TrendingUp, Filter, RefreshCw, Sparkles, Zap, BarChart } from 'lucide-react';
import HotspotCard from '../components/HotspotCard';
import TrendChart from '../components/TrendChart';
import Loading, { HotspotGridSkeleton } from '../components/Loading';
import { getHotspots, getTrendData } from '../services/api';

const HomePage = () => {
  const [hotspots, setHotspots] = useState([]);
  const [trendData, setTrendData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [selectedPlatform, setSelectedPlatform] = useState('全部');

  const platforms = [
    { name: '全部', icon: Sparkles, gradient: 'from-purple-500 to-pink-500' },
    { name: '微博', icon: TrendingUp, gradient: 'from-red-500 to-red-600' },
    { name: '知乎', icon: BarChart, gradient: 'from-blue-500 to-blue-600' },
    { name: '百度', icon: Zap, gradient: 'from-green-500 to-green-600' },
    { name: 'B站', icon: Sparkles, gradient: 'from-pink-500 to-pink-600' },
    { name: '抖音', icon: TrendingUp, gradient: 'from-purple-500 to-purple-600' },
  ];

  const fetchData = async (showRefreshLoader = false) => {
    try {
      if (showRefreshLoader) setRefreshing(true);
      else setLoading(true);

      const [hotspotsData, trendChartData] = await Promise.all([
        getHotspots(selectedPlatform === '全部' ? null : selectedPlatform, false), // useMock=false 使用真实数据
        getTrendData()
      ]);

      setHotspots(hotspotsData);
      setTrendData(trendChartData);
    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [selectedPlatform]);

  const handleRefresh = () => {
    fetchData(true);
  };

  const filteredHotspots = selectedPlatform === '全部' 
    ? hotspots 
    : hotspots.filter(item => item.platform === selectedPlatform);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="mb-8">
            <Loading size="large" text="正在获取最新热点..." />
          </div>
          <HotspotGridSkeleton count={9} />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-r from-blue-400/20 to-purple-600/20 rounded-full blur-3xl animate-float" />
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-r from-purple-400/20 to-pink-600/20 rounded-full blur-3xl animate-float" style={{animationDelay: '1s'}} />
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-60 h-60 bg-gradient-to-r from-indigo-400/10 to-cyan-600/10 rounded-full blur-3xl animate-float" style={{animationDelay: '2s'}} />
      </div>

      <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* 页面标题 */}
        <div className="text-center mb-16 animate-fade-in">
          <div className="flex justify-center mb-6">
            <div className="relative">
              <div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-accent-500 rounded-full blur-xl opacity-30 animate-glow" />
              <div className="relative bg-gradient-to-r from-primary-500 to-accent-500 p-6 rounded-full">
                <TrendingUp className="h-12 w-12 text-white" />
              </div>
            </div>
          </div>
          <h1 className="text-5xl md:text-6xl font-display font-bold mb-4">
            <span className="gradient-text">实时热点</span>
          </h1>
          <p className="text-xl text-gray-600 max-w-2xl mx-auto leading-relaxed">
            全网热点追踪，实时了解最新趋势和话题
          </p>
          <div className="mt-6 flex justify-center">
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="floating-btn flex items-center space-x-3 px-8 py-4 bg-gradient-to-r from-primary-500 to-primary-600 text-white rounded-2xl hover:from-primary-600 hover:to-primary-700 transition-all duration-300 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <RefreshCw className={`h-5 w-5 ${refreshing ? 'animate-spin' : ''}`} />
              <span className="font-semibold">{refreshing ? '刷新中...' : '刷新数据'}</span>
            </button>
          </div>
        </div>

        {/* 趋势图表 */}
        {trendData.length > 0 && (
          <div className="mb-12 animate-slide-up">
            <div className="chart-container">
              <TrendChart data={trendData} title="整体热度趋势" />
            </div>
          </div>
        )}

        {/* 平台筛选 */}
        <div className="glass-effect rounded-3xl p-8 mb-8 animate-slide-up" style={{animationDelay: '0.2s'}}>
          <div className="flex items-center space-x-3 mb-6">
            <div className="p-2 bg-gradient-to-r from-primary-500 to-accent-500 rounded-xl">
              <Filter className="h-5 w-5 text-white" />
            </div>
            <span className="font-bold text-xl text-gray-800">平台筛选</span>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
            {platforms.map((platform) => {
              const Icon = platform.icon;
              const isSelected = selectedPlatform === platform.name;
              return (
                <button
                  key={platform.name}
                  onClick={() => setSelectedPlatform(platform.name)}
                  className={`group relative flex items-center justify-center space-x-2 p-4 rounded-2xl font-semibold transition-all duration-300 ${
                    isSelected
                      ? 'bg-white shadow-lg transform scale-105'
                      : 'hover:bg-white/50 hover:scale-105'
                  }`}
                >
                  <div className={`p-1.5 rounded-xl bg-gradient-to-r ${platform.gradient}`}>
                    <Icon className="h-4 w-4 text-white" />
                  </div>
                  <span className={isSelected ? 'gradient-text' : 'text-gray-700 group-hover:text-gray-900'}>
                    {platform.name}
                  </span>
                  {isSelected && (
                    <div className="absolute inset-0 bg-gradient-to-r from-primary-500/10 to-accent-500/10 rounded-2xl" />
                  )}
                </button>
              );
            })}
          </div>
        </div>

        {/* 热点列表 */}
        {filteredHotspots.length > 0 ? (
          <div className="animate-slide-up" style={{animationDelay: '0.4s'}}>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {filteredHotspots.map((hotspot, index) => (
                <div key={hotspot.id} className="animate-fade-in" style={{animationDelay: `${0.1 * index}s`}}>
                  <HotspotCard
                    hotspot={hotspot}
                    rank={index + 1}
                  />
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="text-center py-20 animate-fade-in">
            <div className="relative inline-block">
              <div className="absolute inset-0 bg-gradient-to-r from-gray-300 to-gray-400 rounded-full blur-xl opacity-20" />
              <TrendingUp className="relative h-20 w-20 text-gray-400 mx-auto mb-6" />
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-4">暂无热点数据</h3>
            <p className="text-gray-600 mb-8 max-w-md mx-auto">
              {selectedPlatform === '全部' ? '当前没有热点数据' : `${selectedPlatform} 平台暂无数据`}
            </p>
            <button
              onClick={handleRefresh}
              className="floating-btn px-6 py-3 bg-gradient-to-r from-primary-500 to-primary-600 text-white rounded-xl hover:from-primary-600 hover:to-primary-700 transition-all duration-300 font-semibold"
            >
              重新获取
            </button>
          </div>
        )}

        {/* 统计信息 */}
        <div className="mt-16 text-center space-y-4 animate-fade-in">
          <div className="glass-effect rounded-2xl p-6 inline-block">
            <p className="text-lg font-semibold text-gray-800">
              共找到 <span className="gradient-text-accent">{filteredHotspots.length}</span> 个热点话题
            </p>
            <p className="text-sm text-gray-600 mt-2">
              数据来源：微博、知乎、百度、B站、抖音等平台
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default HomePage;